import os
import yaml
from pathlib import Path
from typing import Dict, Any
from pydantic import BaseModel

# 定义项目根目录
ROOT_DIR = Path(__file__).parent


class BaseConfig(BaseModel):
    """基礎配置類包含所有網站共享的參數"""
    llm_provider: str = "ollama/deepseek-r1:32b"
    api_base: str = "http://localhost:11435"


def load_yaml_config(file_path: Path) -> Dict[str, Any]:
    """加载YAML配置文件
    
    Args:
        file_path: YAML文件路径
        
    Returns:
        Dict[str, Any]: 配置字典
    """
    try:
        with open(file_path, 'r', encoding='utf-8') as f:
            return yaml.safe_load(f)
    except Exception as e:
        print(f"Error loading config file {file_path}: {e}")
        return {}


def load_base_config() -> Dict[str, Any]:
    """加载基础配置"""
    base_config_path = ROOT_DIR / 'config' / 'base_config.yaml'
    config = load_yaml_config(base_config_path)

    # 如果配置为空，使用BaseConfig的默认值
    if not config:
        config = BaseConfig().model_dump()

    return config


def load_website_configs() -> Dict[str, Dict[str, Any]]:
    """加载所有网站配置"""
    websites_dir = ROOT_DIR / 'config' / 'websites'
    site_configs = {}

    # 确保目录存在
    if not websites_dir.exists():
        print(f"Warning: Websites config directory not found: {websites_dir}")
        return site_configs

    # 加载所有YAML和JSON配置文件
    for file_path in websites_dir.glob('*.yaml'):
        site_name = file_path.stem
        site_configs[site_name] = load_yaml_config(file_path)

    # 也支持JSON配置文件
    for file_path in websites_dir.glob('*.json'):
        site_name = file_path.stem
        site_configs[site_name] = load_yaml_config(file_path)

    return site_configs


# 加载所有配置
SITE_CONFIGS = load_website_configs()

# 从环境变量加载目标网站配置，默认使用theknot_wedding
# ACTIVE_SITE = os.getenv("CRAWLER_ACTIVE_SITE", "theknot_wedding")
ACTIVE_SITE = os.getenv("CRAWLER_ACTIVE_SITE", "yelp_restaurant")

# 确保选择的网站配置存在
if ACTIVE_SITE not in SITE_CONFIGS:
    available_sites = ", ".join(SITE_CONFIGS.keys())
    print(f"Warning: Site '{ACTIVE_SITE}' not found in configurations. Available sites: {available_sites}")
    # 如果没有找到指定的网站配置，使用第一个可用的配置或创建空配置
    ACTIVE_SITE = next(iter(SITE_CONFIGS.keys())) if SITE_CONFIGS else "default"
    if ACTIVE_SITE == "default":
        SITE_CONFIGS["default"] = {}

# 合并基础配置和网站特定配置
active_config = SITE_CONFIGS[ACTIVE_SITE].copy()
active_config.update(load_base_config())
